/**
 * @Author: lll
 * @Email:li.lele@vpclub.cn
 * @Date: create in 2020/7/6
 */
package cn.vpclub.admin.handle;

import cn.vpclub.admin.annotation.MustToken;
import cn.vpclub.admin.entity.UserEntity;
import cn.vpclub.admin.exception.NoPermissionException;
import cn.vpclub.admin.exception.NoTokenException;
import cn.vpclub.admin.exception.TokenWrongException;
import cn.vpclub.admin.mapper.UserMapper;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 全局参数拦截
 *
 * @author lilele
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;
    @Value("${messageDigest.secret}")
    String secret;
    Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        log.info("ServletRequest：{}，资源处理器handle class=={}", httpServletRequest.getServletPath(), handler.getClass());
        /**
         * ResourceHttpRequestHandler拦截静态资源 ，不做处理，可以直接访问
         */
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        /**
         * HandlerMethod拦截相同域名：端口下有@controller注解的bean
         */
        else if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(MustToken.class)) {
                MustToken mustToken = method.getAnnotation(MustToken.class);
                if (mustToken.required() == true) {
                    String token;
                    token = httpServletRequest.getHeader("Authorization");
                    if (token == null) {
                        //抛出NoTokenException异常
                        throw new NoTokenException();
                    }
                    String id;
                    id = JWT.decode(token).getAudience().get(0);
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("id", id);
                    List<UserEntity> list = userMapper.selectList(queryWrapper);
                    //用户信息为空
                    if (list.size() == 0) {
                        //抛出TokenWrongException异常
                        throw new TokenWrongException();
                    }
                    //MustToken注解方法，role字段不匹配与不为admin
                    if (!list.get(0).getRole().equals(mustToken.role()) && !list.get(0).getRole().equals("admin")) {
                        throw new NoPermissionException("无权限！");
                    }
                    Algorithm algorithm = Algorithm.HMAC256(secret);
                    JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer("auth0")
                            .build();
                    //JWT验证token
                    jwtVerifier.verify(token);
                    //拦截器赋值属性userId，转向下一个servlet
                    httpServletRequest.setAttribute("userId", id);
                    return true;
                } else {
                    return true;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception ex) throws Exception {

    }

}
